//
//  SheduleService.m
//  YouthOlympic2014
//
//  Created by Li Yuhang on 14-7-1.
//  Copyright (c) 2014年 mitian. All rights reserved.
//

#import "SheduleService.h"

@implementation SheduleService

///返回某天的日程
//-(NSArray* /*SheduleItem*/) getScheduleItemsByDate:(NSInteger) day{
//    return 0;
//}
-(NSSet* /*SheduleItem*/) getScheduleItemsByDate:(NSInteger) day{
    FMDatabase* db = [DBUtil getDatabase];

    FMResultSet* rs = [db executeQuery:@"select ref_id from schedule where day = ? " withArgumentsInArray:@[[NSNumber numberWithInteger:day]]];
    NSMutableSet* eventIds = [[NSMutableSet alloc]init];
    
    while ([rs next]){
        [eventIds addObject: [rs stringForColumn:@"ref_id"] ];
    }
    
    [rs close];
    [db close];
    return [NSSet setWithSet:eventIds];
}

-(void) getScheduleItemsByDate:(NSInteger) day
                                        completion:(CompletionBlock)completion
{
    //处理超时
    __block BOOL isResultCompletion = NO;
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, RESULT_TIME_MAX * NSEC_PER_SEC);
    dispatch_after(popTime,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        if (!isResultCompletion) {
            isResultCompletion = YES;
            NSString* errorMsg = @"timeout";
            NSError* error = [NSError errorWithDomain:errorMsg code:504 userInfo:nil];
            completion(nil,error);
        }
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSError* error = nil;
        NSMutableDictionary* result = [[NSMutableDictionary alloc] init];
        NSString *gameDate = [NSString stringWithFormat:@"201408%i",day];
        NSDictionary* jsonData = [self.api GetgameDetailInfoByType:@"" andSubType:@"" andGameDate: gameDate withLan:[AppUtils getLan]];
        NSString* errorMsg = [[jsonData objectForKey:@"ApiErrorInfo"] objectForKey:@"msg"];
        
        if (errorMsg != nil) {
            error = [NSError errorWithDomain:errorMsg code:400 userInfo:nil];
        }else{
            NSArray* jsonArr = jsonData[@"GameDetailInfo"];
            //检索数据库，查找已关注的赛事
            FMDatabase* db = [DBUtil getDatabase];
            
            FMResultSet* rs = [db executeQuery:@"select ref_id from schedule where day = ? " withArgumentsInArray:@[[NSNumber numberWithInteger:day]]];
            NSMutableSet* eventIds = [[NSMutableSet alloc]init];
            
            while ([rs next]){
                [eventIds addObject: [rs stringForColumn:@"ref_id"] ];
            }
            [rs close];
            [db close];
            
            //对数据进行加工
            for(int i=0; i<jsonArr.count; i++){
                NSMutableDictionary* item = jsonArr[i];
                NSString* timeStr = item[@"time"]; //20130816133000
                NSDictionary* timeDict = [AppUtils parseApiTimeToDictionary:timeStr];
                //
                NSString* key = [NSString stringWithFormat:@"%@:%@",(NSString*)timeDict[@"hour"],(NSString*)timeDict[@"minute"]];
                if(result[key] == nil){
                    result[key] = [[NSMutableArray alloc]init];
                }
                NSString* eventId = item[@"id"];
                if([eventIds containsObject:eventId])
                {
                    [result[key] addObject:[GameEvent instance:item]];
                }
                
            }
            //移除没用的key
            NSArray *allKeys = [result allKeys];
            for(int i=0;i<[allKeys count];i++){
                NSString *key = [allKeys objectAtIndex:i];
                
                if ([[result objectForKey:key] count]==0) {
                    [result removeObjectForKey:key];
                }
            }
            
            
            NSLog(@"result is: %@",[AppUtils replaceUnicodeDic:result]);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!isResultCompletion) {
                isResultCompletion = YES;
                completion(result,error);
            }
        });
    });
}




-(NSInteger) delScheduleItem:(NSNumber*) scheduleItemId{
    
    FMDatabase* db = [DBUtil getDatabase];
    NSString *sql = @"delete from schedule where ref_id = ?";
    long result =[db executeUpdate:sql, scheduleItemId];
    
    NSLog(@"delScheduleItem result is %ld",result);
    [db close];
    
    return 0;
}

- (NSSet*) getAllStaredDays
{
    FMDatabase* db = [DBUtil getDatabase];
    
    FMResultSet* rs = [db executeQuery:@"select day from schedule"];
    NSMutableSet* allDays = [[NSMutableSet alloc] initWithCapacity:10];

    
    while ([rs next]){
        [allDays addObject:[rs stringForColumn:@"day"]];
    }

    
    NSLog(@"allDays %@",allDays);
    
    
    [rs close];
    [db close];
    
    return allDays;
}

@end
